<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    label-width="150px"
                    :rules="formDataRules"
                    ref="formDataRef"
                >
                    <el-row>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="结算编号">
                                {{ formData.billNo }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="结算日期">
                                <el-date-picker
                                    v-model="formData.billDate"
                                    type="date"
                                    placeholder="选择日期"
                                    value-format="yyyy-MM-dd"
                                    :clearable="false"
                                    v-if="!isRedSingle"
                                >
                                </el-date-picker>
                                <span v-else>{{ formData.billDate }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="合同编号" prop="contractNo">
                                <el-input
                                    v-model="formData.contractNo"
                                    readonly
                                    v-if="!isRedSingle"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="contractNoClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{ formData.contractNo }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="机构" prop="orgName">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="结算单位" prop="settleUnit">
                                {{ formData.settleUnit }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="发票编号" prop="invoice">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.invoice"
                                    v-enterInteger1
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.invoice }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="税率%" prop="taxRate">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxRate"
                                    @input.native="onInput0_100"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'taxRate'
                                    }"
                                    v-if="formData.source !== 0 && !isRedSingle"
                                ></el-input>
                                <!-- 选择的合同的话带入，不可修改 -->
                                <span v-else>{{ formData.taxRate }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="税额(元)" prop="taxPrice">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.taxPrice"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'taxPrice'
                                    }"
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{ formData.taxPrice }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item
                                label="不含税金额(元)"
                                prop="noTaxPrice"
                            >
                                <!-- 结算明细当月金额汇总+进退场费 -->
                                {{ formData.noTaxPrice }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="税价合计(元)"
                                prop="taxRatePrice"
                            >
                                {{ formData.taxRatePrice }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="累计结算金额">
                                {{ formData.accumulativePrice }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="终期结算">
                                <el-checkbox
                                    v-model="formData.totalPrice"
                                    label=""
                                    style="margin-right: 10px"
                                    :disabled="isRedSingle"
                                ></el-checkbox>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item
                                label="冲预付款"
                                prop="rushBeforehandMoney"
                            >
                                <el-checkbox
                                    v-model="formData.rushBeforehandMoney"
                                    label=""
                                    style="margin-right: 10px"
                                    :disabled="isRedSingle"
                                ></el-checkbox>
                            </el-form-item>
                        </el-col>
                        <!-- 首先要选择计划/合同编号后,判断是否做了冲预付款或冲销完了预付款,如果没有那才能勾选,勾选后带出未冲销的预付金额 -->
                        <el-col :span="12">
                            <el-form-item
                                label="冲预付款金额(元)"
                                :prop="
                                    formData.rushBeforehandMoney
                                        ? 'rushBeforehandPrice'
                                        : 'rushBeforehandPrices'
                                "
                            >
                                {{ formData.rushBeforehandPrice }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="币种" prop="currencyId">
                                <el-select
                                    v-model="formData.currencyId"
                                    placeholder="请选择"
                                    @change="currencyChange"
                                    v-if="!isRedSingle"
                                >
                                    <el-option
                                        v-for="item in currencyForm"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                                <span v-else>{{ formData.currency }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{  showState(formData.state) }}
                                <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="冲个人借支">
                                <el-checkbox
                                    v-model="formData.personPurchaseTax"
                                    label=""
                                    style="margin-right: 10px"
                                    :disabled="isRedSingle"
                                ></el-checkbox>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="冲销对象"
                                :prop="
                                    formData.personPurchaseTax
                                        ? 'rushPersonPurchaseTax'
                                        : 'rushPersonPurchaseTaxs'
                                "
                            >
                                <el-input
                                    v-model="formData.rushPersonPurchaseTax"
                                    readonly
                                    v-if="!isRedSingle"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="rushPersonPurchaseTaxClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{
                                    formData.rushPersonPurchaseTax
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row> -->
                    <!-- <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item
                                label="借支人员"
                                :prop="
                                    formData.personPurchaseTax
                                        ? 'person'
                                        : 'persons'
                                "
                            >
                                <el-input
                                    v-model="formData.person"
                                    readonly
                                    v-if="!isRedSingle"
                                >
                                    <i
                                        slot="suffix"
                                        class="
                                            el-input__icon
                                            el-icon-document-copy
                                        "
                                        @click="personClick"
                                    ></i>
                                </el-input>
                                <span v-else>{{ formData.person }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="冲个人借支金额(元)"
                                :prop="
                                    formData.personPurchaseTax
                                        ? 'rushBorrowMoney'
                                        : 'rushBorrowMoneys'
                                "
                            >
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.rushBorrowMoney"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'rushBorrowMoney'
                                    }"
                                    v-if="!isRedSingle"
                                ></el-input>
                                <span v-else>{{
                                    formData.rushBorrowMoney
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row> -->
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="本位币" prop="baseCurName">
                                {{ formData.baseCurName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="本位币汇率">
                                <el-input
                                    placeholder="请填写"
                                    v-model="formData.baseCurRate"
                                    v-enter-float2="{
                                        set: formData,
                                        key: 'baseCurRate'
                                    }"
                                    v-if="!isBaseCurRate && !isRedSingle"
                                    @blur="baseCurRateBlur"
                                ></el-input>
                                <span v-else>{{ formData.baseCurRate }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="人民币汇率">
                                {{ formData.rmbRate }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if='isRedSingle'>
                            <el-form-item label="传输财务共享" prop="share">
                                {{ formData.share }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- <el-row v-if="isRedSingle">
                        <el-col :span="12">
                            <el-form-item label="税价合计(本位币)">
                                {{ formData.taxScSumCost }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="运输单位费用(本位币)">
                                {{ formData.baseCurSettleMoney }}
                            </el-form-item>
                        </el-col>
                    </el-row> -->
                    <!-- <el-row>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="冲预付款金额(本位币)">
                                {{ formData.rushScSumCost }}
                            </el-form-item>
                        </el-col>
                    </el-row> -->
                    <el-row>
                        <el-form-item label="备注">
                            <el-input
                                type="textarea"
                                :rows="2"
                                resize="none"
                                placeholder="请输入内容"
                                v-model="formData.remarks"
                            >
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row v-if="isRedSingle">
                        <el-form-item label="冲红单"
                            ><span :style="redBillStateStyle">{{
                                redBillStateFun
                            }}</span></el-form-item
                        >
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button type="primary" style="background: #2e61d7" @click="save"
                >保存</el-button
            >

            <el-button @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState } from 'vuex'
import { showLoading, hideLoading, formatDate } from '@/utils/common'
import request from '@/api/settlementManagement/equipmentBilling/installSet'
import publics from '@/api/settlementManagement/equipmentBilling/public'

export default {
    data () {
        return {
            //表单数据
            formData: {
                accumulativePrice: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurTotalPrice: 0,
                billDate: formatDate(new Date(), 'yyyy-MM-dd'),
                billId: '',
                billNo: '',
                changeBuySettleId: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                currency: '',
                currencyId: '',
                evaluate: null,
                evaluateGrade: '',
                founderId: '',
                founderName: '',
                freight: 0,
                freightScSumCost: 0,
                invoice: '',
                isRed: false,
                noTaxPrice: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDesciption: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                person: '',
                personPurchaseTax: false,
                purchaseTax: 0,
                purchaseTaxNum: '',
                redBillState: null,
                remarks: '',
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbSumTotalPrice: 0,
                rushBeforehandMoney: false,
                rushBeforehandPrice: 0,
                rushBorrowMoney: 0,
                rushPersonPurchaseTax: '',
                rushPersonPurchaseTaxId: '',
                rushPinAmount: 0,
                rushScSumCost: 0,
                settleUnit: '',
                share: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                taxPrice: 0,
                taxRate: '',
                taxRatePrice: 0,
                taxScSumCost: 0,
                totalPrice: false,
                workId: ''
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转

            formDataRules: {
                settleUnit: [
                    {
                        required: true,
                        message: '请选择结算单位',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxPrice: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                noTaxPrice: [
                    {
                        required: true,
                        message: '请输入不含税金额',
                        trigger: 'blur'
                    }
                ],
                taxRatePrice: [
                    {
                        required: true,
                        message: '请输入税价合计',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'blur' }
                ],
                invoice: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请选择本位币',
                        trigger: 'blur'
                    }
                ],
                rushPersonPurchaseTax: [
                    {
                        required: true,
                        message: '请选择冲销对象',
                        trigger: 'blur'
                    }
                ],
                person: [
                    {
                        required: true,
                        message: '请选择借支人员',
                        trigger: 'blur'
                    }
                ],
                rushBorrowMoney: [
                    {
                        required: true,
                        message: '请填写冲个人借支金额(元)',
                        trigger: 'blur'
                    }
                ],
                rushBeforehandPrice: [
                    {
                        required: true,
                        message: '请填写冲预付金额(元)',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请填写本位币汇率',
                        trigger: 'blur'
                    }
                ],
                contractNo: [
                    {
                        required: true,
                        message: '请选择合同编号',
                        trigger: 'blur'
                    }
                ]
            },
            isRedSingle: false,
            redFormData: null,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isBaseCurRate: true,
            equipmentQuery: {
                query: '',
                id: '',
                source: ''
            },
            rushBeforehandPrice: '',
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        //状态

        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        // // 税额 = 不含税金额*税率
        // 'formData.noTaxPrice' () {
        //     this.formData.taxPrice = (
        //         +this.formData.noTaxPrice *
        //         (+this.formData.taxRate / 100)
        //     ).toFixed(2)
        // },
        // // 税额 = 不含税金额*税率
        // 'formData.taxRate' () {
        //     this.formData.taxPrice = (
        //         +this.formData.noTaxPrice *
        //         (+this.formData.taxRate / 100)
        //     ).toFixed(2)
        // },
        // // 监听税额, 税价合计 = 税额 + 不含税金额
        // 'formData.taxPrice' () {
        //     this.formData.taxRatePrice =
        //         (((+this.formData.taxPrice * 100) + (+this.formData.noTaxPrice * 100)) / 100).toFixed(2)
        // },
        // // 运输单位费用(本位币)
        // 'formData.baseCurSettleMoney' () {
        //     this.formData.baseCurSettleMoney =
        //         +this.formData.freightFee * +this.formData.baseCurRate
        // },
        // // 冲预付款金额(本位币)
        // 'formData.rushBeforehandPrice' () {
        //     this.formData.rushScSumCost =
        //         +this.formData.rushBeforehandPrice * +this.formData.baseCurRate
        // },
        // // 税价合计
        // 'formData.taxRatePrice' () {
        //     this.formData.taxScSumCost =
        //         (+this.formData.taxRatePrice * +this.formData.baseCurRate).toFixed(2)
        // },
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        // 如果勾选中冲个人借支,冲销对象 借支人员 冲个人借支金额必填,否则清除提示信息
        'formData.personPurchaseTax' () {
            if (!this.formData.personPurchaseTax) {
                this.$refs.formDataRef.clearValidate('rushPersonPurchaseTax')
                this.$refs.formDataRef.clearValidate('person')
                this.$refs.formDataRef.clearValidate('rushBorrowMoney')
                this.formData.rushPersonPurchaseTax = ''
                this.formData.person = ''
                this.formData.rushBorrowMoney = ''
            }
        },
        // 如果做了冲预付款或冲销完了预付款,则不能勾选中冲预付款
        'formData.rushPinAmount' () {
            if (this.formData.rushPinAmount) {
                this.formData.rushBeforehandMoney = false
            }
        },
        // 冲预付款勾选中,冲预付款金额必填
        'formData.rushBeforehandMoney' () {
            if (this.formData.rushBeforehandMoney) {
                // 勾选中,需要带出冲预付款金额
                this.formData.rushBeforehandPrice = this.formData.rushPinAmount
            } else {
                this.$refs.formDataRef.clearValidate('rushBeforehandPrice')
                this.formData.rushBeforehandPrice = ''
            }
        },

        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    components: {},
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.formData.orgName = this.orgName
        this.formData.orgId = this.orgId
        const { baseCyByOrgId } = this.userInfo
        this.formData.baseCurName = baseCyByOrgId.currencyName //本位币
        this.formData.baseCurId = baseCyByOrgId.currency
        this.$route.query.isRedSingle === '1'
            ? (this.isRedSingle = true)
            : (this.isRedSingle = false)
        // console.log(typeof this.$route.query.isRedSingle)
        if (this.isRedSingle) {
            this.getRedList()
        }
    },
    methods: {
        // 如果是点击冲红单进入的新增页,则需要返显数据,只有备注能修改,其余均不能修改
        async getRedList () {
            showLoading()
            try {
                let data = await request.redSingle(this.$route.query.billid)
                this.redFormData = this._.cloneDeep(data)
                this.formData = data
            } finally {
                hideLoading()
            }
        },
        // 合同编号
        async contractNoClick () {
            let res = await request.getContractNo(this.equipmentQuery)
            if (res.length < 1) {
                this.formData.contractNo = ''
                this.formData.contractId = ''
                this.formData.taxRate = ''
                this.formData.accumulativePrice = ''
                this.formData.settleUnit = ''
                return
            }
            let data = res[0]
            if (this.formData.contractId !== data.contractId) {
                this.equipmentQuery.source = data.source // 需要传给弹窗的
                this.formData.contractNo = data.contractNo // 合同编号
                this.formData.contractId = data.contractId // 合同编号
                this.formData.taxRate = data.taxRate // 税率,选择的合同的话带入，不可修改
                this.formData.accumulativePrice = data.amount // 累计结算金额
                this.formData.settleUnit = data.leaseOrgName // 结算单位
            }
        },

        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.$message.warning('只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },

        // 点击冲销对象
        rushPersonPurchaseTaxClick () {},
        // 点击借支人员
        async personClick () {
            let res = await publics.getBorrow()
            this.formData.person = res[0].userName
        },
        // 当币种切换时,获取人民币汇率
        async currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种名称
            try {
                let res =  await publics.getRmbRate({
                //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                this.formData.rmbRate = res.rate
            }catch(err) {
                this.formData.rmbRate = ''
            }
        },
        // 本位币汇率不能为0
        baseCurRateBlur () {
            if (this.formData.baseCurRate == 0) {
                this.formData.baseCurRate = null
            }
            this.formData.taxScSumCost =
                +(+this.formData.taxRatePrice * (+this.formData.baseCurRate / 100)).toFixed(2)
            this.formData.rushScSumCost =
                +(+this.formData.rushBeforehandPrice * (+this.formData.baseCurRate / 100)).toFixed(2)
        },

        //保存按钮
        save () {
            this.$refs.formDataRef.validate(valid => {
                if (!valid) return false
                if (this.isRedSingle) {
                    this.redFormData.remarks = this.formData.remarks
                }
                request
                    .basicInfoAdd(
                        this.isRedSingle ? this.redFormData : this.formData
                    )
                    .then( res => {
                        this.clientPop(
                            'info',
                            '保存成功,是否继续',
                            () => {
                                this.$router.replace({
                                    path: '/installSetEdit',
                                    query: {
                                        billid: res,
                                        // name: 'billingDetails'
                                    }
                                })
                            },
                            null,
                            this.handleClose
                        )
                    })
            })
        },
        //取消按钮
        handleClose () {
            this.$router.replace('/installSetList')
        },
        showState (state) {
            const _state = this.$store.state.equip.equipData.settleState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
</style>
